<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/19
 * Time: 21:55
 */

use cza\base\models\statics\OperationEvent;
use yii\bootstrap\Modal;
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use cza\base\widgets\ui\adminlte2\InfoBox;
use cza\base\models\statics\EntityModelStatus;
use yii\helpers\Url;

$regularLangName = \Yii::$app->czaHelper->getRegularLangName();
$messageName = $model->getMessageName();

\backend\assets\ChartAsset::register($this);
$jsonData = $amoebaModel->getAmoebaFormJson(['withMember' => true]);
?>

<h2><?= Yii::t('app.c2', 'Parent Amoeba') ?></h2>
<div id="parent-chart-container"></div>

<h2><?= $amoebaModel->name ?></h2>
<div id="chart-container">
    <?=
    $jsonData == null ? Html::button(Yii::t('app.c2', 'Init'), [
        'class' => 'btn btn-warning btn-block', 'id' => 'btn-init']) : ''
    ?>
</div>

<?php
$form = ActiveForm::begin([
    'action' => ['assign-member-with-chart', 'amoeba_id' => $model->amoeba_id, 'id' => $model->id],
    'options' => [
        'id' => $model->getBaseFormName(),
        'data-pjax' => true,
    ]]);
?>

<div class="<?= $model->getPrefixName('form') ?>
">
    <?php if (Yii::$app->session->hasFlash($messageName)): ?>
        <?php if (!$model->hasErrors()) {
            echo InfoBox::widget([
                'withWrapper' => false,
                'messages' => Yii::$app->session->getFlash($messageName),
            ]);
        } else {
            echo InfoBox::widget([
                'defaultMessageType' => InfoBox::TYPE_WARNING,
                'messages' => Yii::$app->session->getFlash($messageName),
            ]);
        }
        ?>
    <?php endif; ?>

    <div class="well">
        <?php
        echo Form::widget([
            'model' => $model,
            'form' => $form,
            'columns' => 2,
            'attributes' => [
                'user_id' => [
                    'type' => Form::INPUT_WIDGET,
                    'widgetClass' => '\kartik\widgets\Select2',
                    'options' => [
                        'language' => Yii::$app->language,
                        'initValueText' => $model->isNewRecord ? "" : $model->user->username,
                        'options' => [
                            'multiple' => false,
                            'placeholder' => Yii::t('app.c2', 'Search {s1}', ['s1' => Yii::t('app.c2', 'User')]),
                        ],
                        'pluginOptions' => [
                            'allowClear' => true,
                            'minimumInputLength' => 1,
                            'ajax' => [
                                'url' => \yii\helpers\Url::toRoute('search-user'),
                                'dataType' => 'json',
                                'data' => new \yii\web\JsExpression('function(params) { return {q:params.term}; }')
                            ],
                            'escapeMarkup' => new \yii\web\JsExpression('function (markup) { return markup; }'),
                            'templateResult' => new \yii\web\JsExpression('function(data) { return data.text; }'),
                            'templateSelection' => new \yii\web\JsExpression('function (data) { return data.text; }'),
                        ],
                    ],
                ],
                'label' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('label')]],
                'seo_code' => ['type' => Form::INPUT_TEXT, 'options' => ['readonly' => true, 'placeholder' => $model->getAttributeLabel('seo_code')]],
                // 'state' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => '\kartik\checkbox\CheckboxX', 'options' => [
                //     'pluginOptions' => ['threeState' => false],
                // ],],
                // 'status' => ['type' => Form::INPUT_DROPDOWN_LIST, 'items' => EntityModelStatus::getHashMap('id', 'label')],
                'amoeba_id' => [
                    'type' => Form::INPUT_TEXT,
                    'options' => [
                        'readonly' => true,
                        'value' => $model->amoeba_id,
                        'placeholder' => $model->getAttributeLabel('amoeba_id')
                    ]
                ],
                'amoeba_form_id' => [
                    'type' => Form::INPUT_TEXT,
                    'options' => [
                        'readonly' => true,
                        'id' => 'amoeba_form_id',
                        'placeholder' => $model->getAttributeLabel('amoeba_form_id')
                    ]
                ],
                'position' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => '\kartik\touchspin\TouchSpin', 'options' => [
                    'pluginOptions' => [
                        'buttondown_txt' => '<i class="glyphicon glyphicon-minus-sign"></i>',
                        'buttonup_txt' => '<i class="glyphicon glyphicon-plus-sign"></i>',
                    ],
                ],],
            ]
        ]);
        echo Html::beginTag('div', ['class' => 'box-footer']);
        echo Html::submitButton('<i class="fa fa-save"></i> ' . Yii::t('app.c2', 'Save'), ['type' => 'button', 'class' => 'btn btn-primary pull-right']);
        echo Html::a('<i class="fa fa-arrow-left"></i> ' . Yii::t('app.c2', 'Go Back'), ['index'], ['data-pjax' => '0', 'class' => 'btn btn-default pull-right', 'title' => Yii::t('app.c2', 'Go Back'),]);
        echo Html::endTag('div');
        ?>
    </div>
</div>
<?php ActiveForm::end(); ?>

<?php

\yii\bootstrap\Modal::begin([
    'id' => 'content-modal',
    'size' => 'modal-lg'
]);

\yii\bootstrap\Modal::end();

?>

<script type="text/javascript">
    // JQuery.notConfit();
    $(function ($) {
        var datascource = <?=$parentAmoebaModel->getAmoebaFormJson(['withMember' => true]) ?>;

        var nodeTemplate = function (data) {
            var tag = `<div class="title" data-id="${data.id}" data-type="${data.type}">${data.name}</div>`;
            tag += `<div class="warpper">`;
            if (data.memberList) {
                data.memberList.map(function (item) {
                    tag += `<a href="javascript:;" data-uid="${item.user.id}" data-pjax='0' class="kpi glyphicon glyphicon-eye-open">${item.user.username}</a>`
                })
            }
            tag += '</div>';
            return tag;
        };

        var oc = $('#parent-chart-container').orgchart({
            'data': datascource,
            'chartClass': 'edit-state',
            'exportButton': true,
            'exportFilename': 'SportsChart',
            'parentNodeSymbol': 'fa-th-large',
            'pan': true,
            'zoom': true,
            'nodeTemplate': nodeTemplate
        });

        $('.kpi').on('click', function (e) {
            var href = "<?= \yii\helpers\Url::toRoute('member-kpi') ?>"
                + '?user_id=' + jQuery(e.currentTarget).attr('data-uid')
                + '&amoeba_id=' + <?= $parentAmoebaModel->id ?>;
            jQuery('#content-modal').modal('show').find('.modal-content').html('....').load(href);
        });

    });
</script>

<script type="text/javascript">
    // JQuery.notConfit();
    $(function ($) {

        var datascource = <?= $jsonData == null ? "{}" : $jsonData ?>;

        var nodeTemplate = function (data) {
            var tag = `<div class="title" data-id="${data.id}" data-type="${data.type}">${data.name}</div>`;
            tag += `<div class="warpper">`;
            if (data.memberList) {
                data.memberList.map(function (item) {
                    tag += `<a href="javascript:;" data-id="${item.id}" data-pjax='0'
                                class="remove glyphicon glyphicon-remove">${item.user.username}</a>`
                })
            }
            tag += '</div>';
            return tag;
        };

        var oc1 = $('#chart-container').orgchart({
            'data': datascource,
            'chartClass': 'edit-state',
            'exportButton': true,
            'exportFilename': 'SportsChart',
            'parentNodeSymbol': 'fa-th-large',
            'pan': true,
            'zoom': true,
            'nodeTemplate': nodeTemplate
        });
        oc1.$chartContainer.on('click', '.node', function () {
            var $this = $(this);
            var selectedId = $this.find('.title').attr('data-id');
            $('#amoeba_form_id').val(selectedId);
        });

        oc1.$chartContainer.on('click', '.orgchart', function (event) {
            if (!$(event.target).closest('.node').length) {
                $('#selected-node').val('');
            }
        });

        $('#btn-init').on('click', function () {
            if (confirm('你确定要初始化吗？')) {
                $.post("<?= \yii\helpers\Url::toRoute(['init-amoeba-form']) ?>", {'id': <?= $amoebaModel->id ?>}, function (result) {
                    if (result._meta.result === '<?= \cza\base\models\statics\OperationResult::SUCCESS ?>') {
                        location.reload();
                    } else {
                        alert(result._meta.message);
                    }
                })
            }
        });

        $('.remove').on('click', function () {
            if (confirm('你确定要删除吗？')) {
                var elem = $(this);
                var id = elem.attr('data-id');
                $.get("<?= \yii\helpers\Url::toRoute('delete') ?>", {'id': id}, function (result) {
                    if (result._meta.result === '<?= \cza\base\models\statics\OperationResult::SUCCESS ?>') {
                        elem.hide();
                    } else {
                        alert(result._meta.message);
                    }
                })
            }
        });

    });
</script>